﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using Caliburn.Core.InversionOfControl;
using Caliburn.PresentationFramework.Screens;
using MTGenome.MTG;
using Caliburn.PresentationFramework.Invocation;
using MTGenome.UI;
using System.Windows.Media;

namespace MTGenome.ViewModels
{
    [PerRequest(typeof(CardInPlayViewModel)), PartCreationPolicy(CreationPolicy.NonShared)]
    public sealed class CardInPlayViewModel : HaveSubject<ICard>
    {
        private static readonly ImageSource _blankCard = ImageLoader.Load("pack://application:,,,/Embed/BlankCard.jpg");

        private readonly IGathererServer _gatherer;
        private bool _tapped = false;

        public CardInPlayViewModel(IGathererServer gatherer)
        {
            _gatherer = gatherer;

            Image = _blankCard;
        }

        public bool Tapped
        {
            get { return _tapped; }
            set { _tapped = value; NotifyOfPropertyChange(() => Tapped); }
        }

        public string Name
        {
            get { return Subject.Name; }
        }

        public string ManaCost
        {
            get { return Subject.ManaCost; }
        }

        public string PowerToughness
        {
            get { return Subject.PowerToughnessText; }
        }

        public ImageSource Image
        {
            get;
            private set;
        }

        public CardInlineViewModel[] Text
        {
            get;
            private set;
        }

        public void ToggleTapped()
        {
            Tapped = !Tapped;
        }

        public override IHaveSubject<ICard> WithSubject(ICard subject)
        {
            base.WithSubject(subject);

            int index = 0;
            Text = Subject.Text
                .Split('[', ']')
                .Select(t => new CardInlineViewModel(t, (index++ % 2) == 1))
                .Where(c => !string.IsNullOrEmpty(c.Text))
                .ToArray();

            Execute.OnBackgroundThread(() =>
            {
                string path = null;
                try
                {
                    path = _gatherer.GetImagePath(Subject.MultiverseID);
                    if (string.IsNullOrEmpty(path))
                    {
                        return;
                    }

                    Execute.OnUIThread(() =>
                    {
                        Image = ImageLoader.Load(path, 223, 310);
                        NotifyOfPropertyChange(() => Image);
                    });
                }
                catch (Exception exc)
                {
                    Console.WriteLine("Error with Image: {0} {1}", System.IO.Path.GetFileName(path), exc.Message);
                }
            });

            return this;
        }
    }
}
